<template>
  <div class="content">
    <div class="topBox">
      <svg-icon
          @click="backPage"
          :name="'icon-backArrow'"
          class-name="backArrow-svg-icon"
      ></svg-icon>
      <span class="topTitle">{{ title }}</span>
      <span class="znBox">{{ ['智能质检', '标签质检'][templateType] }}</span>
      <span class="scoreBox" v-if="templateType === 1">{{templateScore}}分</span>
      <span class="scoreBox" v-if="templateScore === 100 && templateType === 0">{{templateScore}}分</span>
      <span class="scoreBox2" v-if="templateScore < 100 && templateType === 0">{{templateScore}}分 智能质检模板总分需满足100分</span>
    </div>
    <div class="bottomBox" ref="bottomBox">
      <div class="leftBox">
        <div class="itemTop">
          <span>质检项</span>
          <t-button theme="default" variant="text" @click="handelMenu({})" v-permission="['inspection:save']">
            <template #icon>
              <svg-icon
                  :name="'icon-add'"
                  class-name="add-svg-icon"
              ></svg-icon>
            </template>
            质检项
          </t-button>
        </div>
        <div class="line"></div>
        <div class="itemList">
          <t-menu v-if="menuState.activeMenu" theme="light" :default-value="menuState.activeMenu" width="195px" @change="changeHandler">
            <template v-for="item in menuState.menuList" :key="item.inspectionItemId">
              <t-menu-item :value="item.inspectionItemId">
                <span class="menuName">{{ item.name }}</span>
                <span class="handleBox">
                <svg-icon
                    v-permission="['inspection:update']"
                    @click.stop="handelMenu(item)"
                    :name="'icon-itemEdit'"
                    class-name="item-svg-icon"
                ></svg-icon>
                <svg-icon
                    v-permission="['inspection:delete']"
                    @click.stop="handleMenuDel(item)"
                    :name="'icon-itemDel'"
                    class-name="item-svg-icon"
                ></svg-icon>
              </span>
              </t-menu-item>
            </template>
          </t-menu>
        </div>
      </div>
      <div class="rightBox">
        <div class="topBox" ref="topBox">
          <div class="leftTitle">
            质检规则
            <span class="titleScore">{{ruleScore}}分</span>
          </div>
          <div class="rightHandleBox">
            <t-button
                class="addBtn hoverBlue"
                :disabled="menuState.activeMenu === null"
                theme="primary"
                @click="handleRuleDrawer(true, {})"
                v-permission="['qualityRule:save']"
            >
              <template #icon>
                <svg-icon
                    :name="'icon-add'"
                    class-name="add-svg-icon"
                ></svg-icon>
              </template>
              新增规则
            </t-button>
          </div>
        </div>
        <div class="tableBox">
          <div style="position: relative">
            <t-enhanced-table
                :loading="isLoading"
                ref="tableRef"
                :height="tableHeight"
                v-model:expandedTreeNodes="expandedTreeNodes"
                row-key="qualityRuleId"
                drag-sort="row-handler"
                :data="tableState.tableData"
                :columns="tableState.columns"
                :tree="tableState.treeConfig"
                :expand-icon="expandIcon"
                :treeExpandAndFoldIcon="treeExpandIcon"
                lazy-load
                @expanded-tree-nodes-change="onExpandedTreeNodesChange"
            >
              <template #handle="{ row }">
                <t-button
                    theme="primary"
                    v-if="!row['qualityRuleList'] && row.fatal !== 1 && !row.level"
                    class="rowAdd_o"
                    @click="handleNewChild(row, 0)"
                    v-permission="['inspection:update']"
                >
                  <template #icon>
                    <svg-icon
                        :name="'icon-orangeAdd'"
                        class-name="row-svg-icon"
                    ></svg-icon>
                  </template>
                  创建子级
                </t-button>

                <t-button
                    theme="primary"
                    v-if="row['qualityRuleList'] && row['qualityRuleList'].length > 0 "
                    class="rowAdd_g"
                    @click="handleNewChild(row , 1)"
                    v-permission="['inspection:update']"
                >
                  <template #icon>
                    <svg-icon
                        :name="'icon-greenAdd'"
                        class-name="row-svg-icon"
                    ></svg-icon>
                  </template>
                  新增子级
                </t-button>

                <t-button theme="primary" v-if="row.level === 2" class="secureBtn" @click="handleSecure(row)" v-permission="['inspection:update']">
                  <template #icon>
                    <svg-icon
                        :name="'icon-secure'"
                        class-name="row-svg-icon"
                    ></svg-icon>
                  </template>
                  解除关系
                </t-button>

                <t-button theme="primary" class="rowEdit" @click="handleRuleDrawer(false, row)" v-permission="['qualityRule:update']">
                  <template #icon>
                    <svg-icon
                        :name="'icon-rowEdit'"
                        class-name="row-svg-icon"
                    ></svg-icon>
                  </template>
                  编辑
                </t-button>

                <t-button theme="primary" class="rowDel" @click="handleRuleDel(row)" v-permission="['qualityRule:delete']">
                  <template #icon>
                    <svg-icon
                        :name="'icon-rowDel'"
                        class-name="row-svg-icon"
                    ></svg-icon>
                  </template>
                  删除
                </t-button>
              </template>
            </t-enhanced-table>
            <div class="emptyBox" v-if="tableState.tableData.length === 0">
              <svg-icon
                  :name="'icon-emptyTable'"
                  class-name="emptyTable-svg-icon"
              ></svg-icon>
              <span>暂无数据</span>
            </div>
          </div>
        </div>
        <div class="footerBox">
          <t-pagination
              v-model="current"
              v-model:pageSize="pageSize"
              :pageSizeOptions="[10, 20, 30, 50]"
              :total="totalNum"
              size="small"
              show-jumper
              @page-size-change="onPageSizeChange"
              @current-change="onCurrentChange"
          />
        </div>
      </div>
    </div>

<!--      新增 编辑 质检项-->
    <t-dialog
        v-model:visible="addModuleVisible"
        class="ruleDialog"
        width="385"
        :header="moduleTitle"
        :onClose="onClose"
    >
      <t-form
          ref="ruleForm"
          :data="ruleData"
          :label-align="'top'"
          :rules="AHEAD_RULES"
          @reset="ruleReset"
          @submit="ruleSubmit">
        <t-form-item label="质检项名称" name="name">
          <t-input
              v-model="ruleData.name"
              v-noSpace="ruleData.name"
              :maxlength="9"
              show-limit-number placeholder="请输入质检项名称">
          </t-input>
        </t-form-item>
        <t-form-item class="handleRuleBox">
          <t-space size="small">
            <t-button theme="default" variant="base" type="reset">取消</t-button>
            <t-button theme="primary" type="submit">保存</t-button>
          </t-space>
        </t-form-item>
      </t-form>
    </t-dialog>

<!--    删除质检项-->
    <t-dialog
        v-model:visible="delVisible"
        theme="info"
        width="431"
        header="您确认删除该质检项吗？"
        body=""
        :on-confirm="onClickConfirm"
    />

    <!--    删除质检项规则-->
    <t-dialog
        v-model:visible="delRuleVisible"
        theme="info"
        width="431"
        header="您确认删除该质检规则吗？"
        body=""
        :on-confirm="onRuleClickConfirm"
    />

<!--    创建子级-->
    <t-dialog
        v-model:visible="addSonVisible"
        :closeOnOverlayClick="false"
        class="createDialog"
        width="483"
        :header="sonTitle"
        :onClose="onClose"
    >
      <t-form
          ref="sonForm"
          :data="sonData"
          :label-align="'top'"
          @reset="sonReset"
          @submit="sonSubmit"
      >
        <div class="outAdd">
          <div class="titleBtn" @click="handleAddSon">
            <svg-icon
                :name="'icon-add'"
                class-name="add-svg-icon"
            ></svg-icon>
            新增子级
          </div>
        </div>
        <div class="scrollBox">
          <div class="outBox" v-for="(item, index) in sonData.bonds">
            <div class="outHeader">
              <div class="left">子级{{ index + 1}}</div>
              <div class="right" v-if="index !== 0">
                <div @click="handleDelSon(index)">
                  <svg-icon
                      :name="'icon-itemDel'"
                      class-name="itemDel-svg-icon"
                  ></svg-icon>
                  删除
                </div>
              </div>
            </div>
            <t-form-item label="选择质检规则" requiredMark>
              <t-select
                  v-model="item.childId"
                  clearable
                  :options="sonOptions.options"
                  placeholder="请选择无关系的规则"
                  @focus="handleFocus"
                  @change="handleChange"
              >
                <template v-for="(item, index) in secureVisible" :key="index">
                  <t-option :disabled="item.disabled" :label="item.label"  :value="item.value" />
                </template>

              </t-select>
            </t-form-item>
            <t-form-item label="级关系" requiredMark>
              <t-space style="gap: 8px;">
                <div>
                  <t-select
                      v-model="item.levelMatchType"
                      placeholder="请选择"
                      clearable
                  >
                    <t-option :key="0" label="座席"  :value="0" />
                    <t-option :key="1" label="客户" :value="1" />
                  </t-select>
                </div>

                <div style="font-size: 12px">
                  <span>侧,</span>
                </div>

                <div>
                  <t-input-number
                      class="countInput"
                      theme="normal"
                      v-model="item.levelCount"
                      :min="0"
                      @blur="countBlur"
                      placeholder="请输入">
                  </t-input-number>
                </div>

                <div>
                  <t-select
                      v-model="item.levelType"
                      placeholder="请选择"
                      clearable
                  >
                    <t-option :key="0" label="句"  :value="0" />
                    <t-option :key="1" label="秒" :value="1" />
                  </t-select>
                </div>

                <div>
                  <span>内,需触发子级规则</span>
                </div>
              </t-space>
            </t-form-item>
          </div>
        </div>
        <t-form-item class="handleRuleBox">
          <t-space size="small">
            <t-button theme="default" variant="base" type="reset">取消</t-button>
            <t-button theme="primary" type="submit">保存</t-button>
          </t-space>
        </t-form-item>
      </t-form>
    </t-dialog>

<!--    解除关系-->
    <t-dialog
        v-model:visible="secureVisible"
        theme="info"
        width="431"
        header="您确认解除该关联关系吗？"
        body=""
        :on-confirm="onSecureClickConfirm"
    />

    <rule-drawer
        :drawerVisible="drawerVisible"
        :drawerTitle="drawerTitle"
        @resetDrawerVisible="resetDrawerVisible"
        :templateId="JSON.parse(cache.getSession('templateInfo'))['id']"
        :inspectionItemId="menuState.activeMenu"
        :qualityRuleId="qualityRuleId"
        :templateScore="templateScore"
    ></rule-drawer>
  </div>
</template>

<script setup lang="jsx">
import {computed, getCurrentInstance, nextTick, onMounted, onUnmounted, reactive, ref, toRaw, watch, isRef} from "vue";
import {debounce} from "../../../utils/tools";
import {MessagePlugin} from "tdesign-vue-next";
const pageInstance = getCurrentInstance()
import RuleDrawer from "./components/ruleDrawer.vue";
import { useRouter, useRoute } from "vue-router";
import _ from 'lodash';
import {
  delInspection, delQualityRule,
  editInspection, getTemplateScore,
  inspectionDetail, getRuleScore,
  inspectionList,
  newInspection, ruleList,
  getNoRelationshipList,
  addLevel,
  releaseLevel
} from "../../../api/qualitySet/qualityTemplate";
import cache from '@/utils/cache.js'
import {usePageStore} from "../../../pinia/page";
import {
  ChevronRightCircleIcon,
  ChevronDownCircleIcon
} from 'tdesign-icons-vue-next';

const router = useRouter()
const route = useRoute()
const title = ref('') // 模版名称
const templateType = ref() // 模版名称
title.value = JSON.parse(cache.getSession('templateInfo'))['templateName']
templateType.value = JSON.parse(cache.getSession('templateInfo'))['type']

// 返回
const backPage = () => {
  router.push('/qualitySet/qualityTemplate')
}
// 路由变化
let once = ref(true)
watch(() =>router.currentRoute.value.path,(newValue,oldValue)=> {
  if(once.value) {
    once.value = false
  }
},{ immediate: true })
// 抽屉
const drawerVisible = ref(false)
const drawerTitle = ref('')
const qualityRuleId = ref('')
const handleRuleDrawer = (flag, data) => { // 新增、编辑规则
  drawerTitle.value = flag ? '新增规则' : '编辑规则'
  qualityRuleId.value = flag ? '' : data['qualityRuleId']
  drawerVisible.value = true
}
const resetDrawerVisible = (flag) => {
  drawerVisible.value = false
  if(flag) {
    handleQuery(menuState.activeMenu)
    getScoreTemplate()
  }

}


// 左侧导航
const activeMenu = ref('')
const menuState = reactive({
  activeMenu: null,
  menuList: []
})

const changeHandler = (active) => {
  menuState.activeMenu = active
  handleQuery(active)
}


// 创建/新增子级弹窗
const addSonVisible = ref(false)
const sonTitle = ref('')
const sonOptions = reactive({
  options: []
})
const sonData = reactive({
  bonds: [
    {
      fatherId: '',
      childId: null,
      inspectionItemId: '',
      levelCount: null,
      levelMatchType: null,
      levelType: null,
      templateId: null,
    }
  ],
});

// 创建子级
const allChildData = ref() // 当前所有选项
const currentRow = ref() // 当前点击的行

const handleNewChild = (row, type) => {
  currentRow.value = row
  let data = {
    templateId: JSON.parse(cache.getSession('templateInfo'))['id'],
    inspectionId: menuState.activeMenu,
    id: row.qualityRuleId
  }
  getNoRelationshipList(data).then(res => {
    sonTitle.value = type === 0 ? '创建子级' : '新增子级'
    addSonVisible.value = true
    allChildData.value = res.data
    sonOptions.options = res.data.map(item => {
      return {
        label: item.qualityRuleName,
        value: item.qualityRuleId,
        disabled: false,
      }
    })
  })
}

const countBlur = (value) => {
  if(value && value < 0) {
    MessagePlugin.error('请输入正数！')
  }
}

// 新增子集
const handleAddSon = () => {
  let obj = {
    fatherId: '',
    childId: null,
    inspectionItemId: '',
    levelCount: null,
    levelMatchType: null,
    levelType: null,
    templateId: null,
  }
  sonData['bonds'].push(obj)
}
// ----------⬇ ------------
// 已选中的质检规则不可再次选中
const focusValue = ref()
const handleFocus = (e) => {
  focusValue.value = e.value
  sonOptions.options.forEach(item => {
    sonData.bonds.forEach(son => {
      if(son.childId === item.value) {
        item.disabled = true
      }
    })
  })
}
const handleChange = (e) => {
  if(focusValue.value) {
    sonOptions.options.forEach(item => {
      if(item.value === focusValue.value) {
        item.disabled = false
      }
    })
  }
}
// ----------⬆ ------------

// 删除子集
const handleDelSon = (i) => {
  sonData['bonds'] = sonData['bonds'].filter((item, index) => {
    return index !== i
  })
}
// 检测子集是否都配置完毕
const checkBondsPro = (ary) => {
  return new Promise((resolve, reject) => {
    ary.forEach((item, index) => {
      if(item.childId === null || item.childId === undefined ||
          item.levelMatchType === null || item.levelMatchType === undefined ||
          item.levelType === null || item.levelType === undefined ||
          item.levelCount === null || item.levelCount === undefined) {
        resolve({flag: false, index: index + 1})
      }
      if(item.levelCount && item.levelCount < 0) {
        resolve({ flag: false, type: 0 })
      }
    })
    resolve({ flag: true })
  })
}

// 创建子集 提交
const sonSubmit = async () => {
  let res = await checkBondsPro(sonData.bonds)
  if (res.flag) { // 是否配置完毕
    sonData.bonds.forEach(item => {
      item.fatherId = currentRow.value['qualityRuleId']
      item.inspectionItemId = JSON.parse(JSON.stringify(menuState.activeMenu))
      item.templateId = JSON.parse(cache.getSession('templateInfo'))['id']
    })

    addLevel(sonData.bonds).then(res => {
      if(res.code === 0) {
        MessagePlugin.success('操作成功！')
        addSonVisible.value = false
        handleQuery(menuState.activeMenu)
        // 重置响应式对象
        // resetReactiveObject(sonData);
        sonData.bonds = []
        let ary = [{
            fatherId: '',
            childId: null,
            inspectionItemId: '',
            levelCount: null,
            levelMatchType: null,
            levelType: null,
            templateId: null,
        }]
        Object.assign(sonData.bonds, ary)
      }
    })
  } else {
    if (res.type === 0) {
      await MessagePlugin.error('请输入正数！')
      return
    }
    let str = `请确认 【子级${res.index}】 是否配置完毕！`
    await MessagePlugin.error(str)
  }
}
const sonReset = () => {
  sonData.bonds = []
  let ary = [{
    fatherId: '',
    childId: null,
    inspectionItemId: '',
    levelCount: null,
    levelMatchType: null,
    levelType: null,
    templateId: null,
  }]
  Object.assign(sonData.bonds, ary)
  pageInstance.refs.sonForm.reset()
  addSonVisible.value = false
}


// 解除关系
const secureVisible = ref(false)
const secureRow = ref()
const handleSecure = (row) => {
  secureRow.value = row
  secureVisible.value = true

}
const onSecureClickConfirm = () => {
  // 子级数据
  let row = JSON.parse(JSON.stringify(secureRow.value))

  let data = {
    childId: row.qualityRuleId,
    fatherId: row.fatherId,
    inspectionItemId: JSON.parse(JSON.stringify(menuState.activeMenu)),
    templateId: JSON.parse(cache.getSession('templateInfo'))['id']
  }

  releaseLevel(data).then(res => {
    if(res.code === 0) {
      secureVisible.value = false
      MessagePlugin.success('解除关系成功！')
      handleQuery(menuState.activeMenu)
    }
  })
}

// 新增、编辑质检项弹窗
const addModuleVisible = ref(false)
const ruleData = reactive({
  templateId: JSON.parse(cache.getSession('templateInfo'))['id'],
  name: ''
});
const AHEAD_RULES = {
  name: [ { required: true, message: '请输入质检项名称' ,type: 'error', trigger: 'blur'}]
}
const moduleTitle = ref('')
const isNewModule = ref(true) // 新增 ｜ 编辑
const itemRulesInfo = ref([])
const handelMenu = (menu) => { // 新增修改质检项
  moduleTitle.value = Object.keys(menu).length === 0 ? '新增质检项' : '编辑质检项'
  isNewModule.value = Object.keys(menu).length === 0
  addModuleVisible.value = true

  // 编辑调用详情接口
  if(!isNewModule.value) {
    let data = {
      templateId: JSON.parse(cache.getSession('templateInfo'))['id'],
      id: menu['inspectionItemId']
    }
    inspectionDetail(data).then(res => {
      nextTick(() => {
        itemRulesInfo.value = res.data
        ruleData.name = res.data.name
      })
    })
  }
}
// 质检项提交
const ruleSubmit = ({ validateResult, firstError }) => {
  if (validateResult === true) {

    if(isNewModule.value) { // 新增质检项
      ruleData.qualityRules = []
      if(ruleData.id) delete ruleData.id
      newInspection(ruleData).then(res => {
        if(res.code === 0) {
          getItemList(true)
          MessagePlugin.success('新增成功！');
        }
        pageInstance.refs.ruleForm.reset()
        addModuleVisible.value = false
      })
    } else { // 编辑质检项
      ruleData.qualityRules = itemRulesInfo.value['qualityRules']
      ruleData.id = itemRulesInfo.value['inspectionItemId']
      editInspection(ruleData).then(res => {
        if(res.code === 0) {
          getItemList(false)
          MessagePlugin.success('编辑成功！');
        }
        pageInstance.refs.ruleForm.reset()
        addModuleVisible.value = false
      })
    }

  } else {
    console.log('Validate Errors: ', firstError, validateResult);
    MessagePlugin.warning(firstError);
  }
};
const ruleReset = () => {
  pageInstance.refs.ruleForm.reset()
  addModuleVisible.value = false
}
const onClose = () => {
  pageInstance.refs.ruleForm.reset()
  addModuleVisible.value = false


  sonData.bonds = []
  let ary = [{
    fatherId: '',
    childId: null,
    inspectionItemId: '',
    levelCount: null,
    levelMatchType: null,
    levelType: null,
    templateId: null,
  }]
  Object.assign(sonData.bonds, ary)
  pageInstance.refs.sonForm.reset()
  addSonVisible.value = false
}
// 删除质检项弹窗
const delVisible = ref(false)
const delId = ref('')
const handleMenuDel = (row) => {
  delVisible.value = true
  delId.value = row['inspectionItemId']
}
const onClickConfirm = (context) => {
      let data = {
        templateId: JSON.parse(cache.getSession('templateInfo'))['id'],
        id:delId.value
      }
      delInspection(data).then(res => {
        MessagePlugin.success('删除成功！');
        // 判断是否删除的是选中的数据
        if(delId.value === menuState.activeMenu) {
          menuState.activeMenu = null
          getItemList(false, true)
        }
        delVisible.value = false;
      }).catch(err => {
        console.log(err)
      })
};

// 删除质检规则弹窗
const delRuleVisible = ref(false)
const ruleDelId = ref('')
const handleRuleDel = (row) => {
  delRuleVisible.value = true
  ruleDelId.value = row['qualityRuleId']
}
const onRuleClickConfirm = (context) => {
  let data = {
    templateId: JSON.parse(cache.getSession('templateInfo'))['id'],
    qualityRuleId: ruleDelId.value
  }
  delQualityRule(data).then(res => {
    MessagePlugin.success('删除成功！');
    handleQuery(menuState.activeMenu)
    getScoreTemplate()
    delRuleVisible.value = false;
  }).catch(err => {
    console.log(err)
  })
};

// 获取质检项列表
const getItemList = (flag, first) => {
  let id = JSON.parse(cache.getSession('templateInfo'))['id']
  inspectionList(id).then(res => {
    menuState.menuList = res.data.inspectionItems
    getScoreTemplate()

    if(flag) {
      if(first && menuState.menuList.length > 0) {
        menuState.activeMenu = res.data.inspectionItems[0]['inspectionItemId']
        handleQuery(res.data.inspectionItems[0]['inspectionItemId'])
      }
        if(!first && menuState.menuList.length === 1) {
            menuState.activeMenu = res.data.inspectionItems[0]['inspectionItemId']
            handleQuery(res.data.inspectionItems[0]['inspectionItemId'])
        }
    } else {
      if(first && menuState.menuList.length > 0) {
        menuState.activeMenu = res.data.inspectionItems[0]['inspectionItemId']
        handleQuery(res.data.inspectionItems[0]['inspectionItemId'])
      }
      if(menuState.menuList.length === 0) {
        menuState.activeMenu = null
        tableState.tableData = []
        ruleScore.value = 0
      }
    }
  })
}

// 获取模版分值
const templateScore = ref(0)
const getScoreTemplate = () => {
  let id = JSON.parse(cache.getSession('templateInfo'))['id']
  getTemplateScore(id).then(res => {
    templateScore.value = res.data
  })
}
// 获取规则分值
const ruleScore = ref(0)
const getScoreRule = () => {
  let data = {
    templateId: JSON.parse(cache.getSession('templateInfo'))['id'],
    id: menuState.activeMenu
  }
  getRuleScore(data).then(res => {
    ruleScore.value = res.data
  })
}

onMounted(() => {
  // set left menu light
  usePageStore().$patch((state) => {
    state.lightMenu = '/qualitySet/qualityTemplate'
  })
  getItemList(true, true)
})

// 分页
const current = ref(1);
const pageSize = ref(10);
const totalNum = ref(0)
const onPageSizeChange = (size) => {
  pageSize.value = size
  handleQuery(menuState.activeMenu)
};
const onCurrentChange = (index, pageInfo) => {
  current.value = index
  handleQuery(menuState.activeMenu)
};

// table
//enhanced-table
const expandIcon = ref(false)
const expandedTreeNodes = ref([]);

const tableState = reactive({
  tableData: [],
  columns: [
    { colKey: 'qualityRuleName',title: '规则名称' },
    { colKey: 'sonName',title: '子级规则名称', align: 'left' },
    { colKey: 'initialScore', title: '分值', align: 'left', cell:(h, {row}) => { return row.initialScore + '分'} },
    { colKey: 'fatal', title: '是否致命', align: 'left', cell:(h, {row}) => {
      return (
        row.fatal === 1
          ? <t-tag theme='danger' variant="light-outline">
              是
            </t-tag>
          : <t-tag theme='success' variant="light-outline">
              否
            </t-tag>
        )
      }},
    { colKey: 'createTime', title: '创建时间', align: 'left', width: 200 },
    { colKey: 'handle', title: '操作', align: 'center', width: 290 },
  ],
  treeConfig: {
    childrenKey: 'qualityRuleList',
    treeNodeColumnIndex: 0,
    indent: 250,
    expandTreeNodeOnClick: false,
  }
})
const onExpandedTreeNodesChange = (expandedTreeNodes, context) => {
  console.log(expandedTreeNodes, context);
};
const treeExpandAndFoldIconRender = (h, { type, row }) => {
//   nextTick(() => {
  return type === 'expand' ?  <ChevronRightCircleIcon /> : <ChevronDownCircleIcon />
//   })
//
};
const treeExpandIcon = computed(() => {
  // 自定义展开图标
  return treeExpandAndFoldIconRender;
})



const isLoading = ref(false)
const handleQuery = (id) => {
  isLoading.value = true
  let data = {
    templateId: JSON.parse(cache.getSession('templateInfo'))['id'],
    pageNo: current.value,
    pageSize: pageSize.value,
    id
  }
  ruleList(data).then(res => {
    if(res.code === 0) {
      if(!res.data) {
        isLoading.value = false
        return
      }
      // 格式 个别的数据
      res.data.list.forEach(item => {
        item.sonName = '-'
        if(item['qualityRuleList'] && item['qualityRuleList'].length > 0) {
          item['qualityRuleList'].forEach(e => {
            e.fatherId = item.qualityRuleId // 父级的质检规则id
            e.sonName = e.qualityRuleName
          })
        }
      })
      tableState.tableData = res.data.list
      current.value = res.data['currPage']
      pageSize.value = res.data['pageSize']
      totalNum.value = res.data['totalCount']
      getScoreRule()
    }
    isLoading.value = false
  })
}

// table 高度变化
const tableHeight = ref(0)
const getTableHeight = () => {
  nextTick(() => {
    const windowHeight = window.innerHeight
    tableHeight.value = windowHeight - 290
  })
}

// window窗口 变化
const getWindowInfo = () => {
  const info = {
    width: window.innerWidth,
    height: window.innerHeight
  }
  getTableHeight()
}
const resizeInfo = debounce(getWindowInfo, 300)
onMounted(() => {
  getTableHeight()
  window.addEventListener('resize', resizeInfo);
})
onUnmounted(() => {
  window.removeEventListener('resize', resizeInfo);
})

</script>

<style lang="scss" scoped>
.content {
  background-color: #EBECED !important;
  padding: 8px;
  position: relative;
  overflow: hidden;
  .topBox {
    padding: 0 20px;
    height: 57px;
    line-height: 57px;
    opacity: 1;
    border-radius: 4px;
    background: rgba(255, 255, 255, 1);
    box-shadow: 0 4px 10px 3px rgba(240, 240, 240, 0.05);
    display: flex;
    //justify-content: center;
    align-items: center;
    .topTitle {
      font-size: 16px;
      font-weight: 600;
      color: rgba(51, 51, 51, 1);
    }
    .backArrow-svg-icon {
      height: 16px;
      width: 16px;
      cursor: pointer;
      margin-right: 12px;
    }
    .znBox {
      margin-left: 6px;
      width: 61px;
      height: 19.52px;
      opacity: 1;
      border-radius: 4px;
      background: rgba(255, 246, 230, 1);
      border: 1px solid rgba(255, 153, 0, 1);
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 11px;
      font-weight: 400;
      color: rgba(255, 153, 0, 1);
    }
    .scoreBox {
      margin-left: 16px;
      min-width: 51px;
      padding: 0 9px;
      height: 23px;
      opacity: 1;
      border-radius: 4px;
      background: rgba(255, 246, 230, 1);
      display: flex;
      justify-content: center;
      align-items: center;
      //padding: 7px 8px 7px 8px;

      font-size: 12px;
      font-weight: 600;
      color: rgba(255, 153, 0, 1);
    }
    .scoreBox2 {
      margin-left: 16px;
      width: 211px;
      height: 23px;
      opacity: 1;
      border-radius: 4px;
      background: rgba(255, 237, 237, 1);
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 12px;
      font-weight: 400;
      letter-spacing: 0.56px;
      line-height: 14px;
      color: rgba(227, 77, 89, 1);
    }
  }
  .bottomBox {
    height: calc(100vh - 172px);
    margin-top: 8px;
    display: flex;
    .leftBox {
      height: 100%;
      width: 219px;
      min-width: 219px;
      opacity: 1;
      background: rgba(255, 255, 255, 1);
      border-radius: 4px;
      box-shadow: 0 4px 10px 3px rgba(240, 240, 240, 0.05);
      margin-right: 8px;
      overflow: hidden;
      .itemTop {
        height: 60px;
        padding: 17px 20px 0 18px;
        span {
          font-size: 14px;
          font-weight: 600;
          color: rgba(56, 56, 56, 1);
        }
        :deep(.t-button) {
          font-size: 11px;
          font-weight: 400;
          line-height: 15.4px;
          color: rgba(30, 117, 254, 1);
          text-align: left;
          vertical-align: top;
          height: 22.5px;
          padding: 0;
          float: right;
        }
        :deep(.t-button):hover {
          background-color: unset;
        }
        .add-svg-icon {
          height: 16px;
          width: 16px;
          margin-right: 2px;
        }
      }
      .line {
        height: 0;
        opacity: 1;
        background: rgba(204, 204, 204, 1);
        border: 1px solid rgba(239, 242, 245, 1);
      }
      .itemList {
        height: calc(100% - 42px);
        text-align: center;
        :deep(.t-default-menu) {
          height: calc(100% - 28px)!important;
        }
        :deep(.t-menu) {
          padding-top: 10px;
          padding-bottom: 0;
          .t-menu__item {
            .t-menu__content {
              display: flex;
              width: 100%;
              .menuName {
                font-size: 12px;
                font-weight: 600;
              }
              .handleBox {
                margin-left: auto;
                display: none;
              }
            }
            .item-svg-icon {
              height: 16px;
              width: 16px;
              cursor: pointer;
              margin: 0 4px;
            }
          }
          .t-menu__item:hover {
            .handleBox {
              margin-left: auto;
              display: inline-block;
            }
          }
          .t-is-active {
            background-color: rgba(241, 244, 254, 1);
            border-radius: 3px;
            color: rgba(30, 117, 254, 1);
          }
        }
      }
    }
    .rightBox {
      border-radius: 4px;
      background: rgba(255, 255, 255, 1);
      flex: 1;
      .topBox {
        padding: 0 16px;
        height: 61px;
        display: flex;
        justify-content: center;
        align-items: center;
        .leftTitle {
          font-size: 16px;
          font-weight: 600;
          color: rgba(51, 51, 51, 1);
          text-align: left;
          .titleScore {
            display: inline-block;
            min-width: 44px;
            padding: 0 9px;
            height: 22px;
            line-height: 22px;
            text-align: center;
            opacity: 1;
            border-radius: 4px;
            background: rgba(241, 244, 254, 1);

            font-size: 12px;
            font-weight: 600;
            color: rgba(30, 117, 254, 1);
          }
        }
        .rightHandleBox {
          margin-left: auto;
          .addBtn {
            //float: right;
            width: 101px;
            height: 28px;
            opacity: 1;
            border-radius: 3px;
            background: rgba(30, 117, 254, 1);
            padding: 5px 0;
            font-size: 12px;
            font-weight: 400;
            color: rgba(255, 255, 255, 1);
            .add-svg-icon {
              height: 16px;
              width: 16px;
              margin-right: 7px;
            }
          }
          .t-is-disabled {
            opacity: 0.5;
          }
          .batch {
            margin-right: 10px;
            .t-button {
              width: 106px;
              height: 28px;
              opacity: 1;
              border-radius: 3px;
              background: rgba(227, 238, 255, 1);
              border: 0.5px solid rgba(9.38399999999999, 95.71679999999998, 234.6, 1);
              padding: 5px 0;
              font-size: 12px;
              font-weight: 400;
              color: rgba(30, 117, 254, 1);
              .batch-svg-icon {
                height: 16px;
                width: 16px;
                margin-right: 7px;
              }
            }
          }
        }
      }
      .tableBox {
        :deep(.t-table__header) {
          tr {
            th {
              padding: 7px 10px;
              box-sizing: border-box;
            }
            th:nth-child(1) {
              //min-width: 200px;
              padding-left: 50px;
            }
            //th:nth-child(2) {
            //  padding-left: 90px;
            //}
            th:last-child {
            }
          }
        }
        :deep(.t-table__body) {
          tr {
            td {
              padding: 6px 10px;
              box-sizing: border-box;
            }
            td:nth-child(1) {
              padding-left: 50px;
            }
            //td:nth-child(2) {
            //  padding-left: 90px;
            //}
            td:last-child {
              text-align: right;
              padding-right: 40px;
            }
          }
          .t-button {
            border: none;
            width: 56px;
            height: 26px;
            opacity: 1;
            border-radius: 3px;
            font-size: 13px;
            font-weight: 400;
            padding: 0;
            margin: 0 4px;
            .row-svg-icon {
              height: 12px;
              width: 12px;
              margin-right: 2px;
            }
          }
          .rowDel {
            background: rgba(255, 224, 224, 1);
            color: rgba(227, 77, 89, 1);
          }
          .rowConfig {
            background: rgba(255, 238, 224, 1);
            color: rgba(255, 153, 0, 1);
          }
          .rowEdit {
            background: rgba(227, 238, 255, 1);
            color: rgba(30, 117, 254, 1);
          }
          .rowAdd_o {
            width: 82px !important;
            background: rgba(255, 238, 224, 1);
            color: rgba(255, 153, 0, 1);
            .svg-icon {
              height: 10px;
              width: 10px;
              margin-right: 2px;
            }
          }
          .rowAdd_g {
            width: 82px !important;
            background: rgba(233, 246, 242, 1);
            color: rgba(0, 184, 122, 1);
            .svg-icon {
              height: 10px;
              width: 10px;
              margin-right: 2px;
            }
          }
          .secureBtn {
            width: 82px !important;
            background: rgba(235, 235, 235, 1);
            color: rgba(128, 128, 128, 1);
            .svg-icon {
              height: 10px;
              width: 10px;
              margin-right: 2px;
            }
          }
          .t-tag {
            margin: 0 auto;
            width: 36px;
            height: 24px;
            opacity: 1;
            border-radius: 4px;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 5px 12px 5px 12px;
            font-size: 12px;
            font-weight: 400;
            float: left;
          }
          .t-tag--danger {
            background: rgba(255, 237, 237, 1);
            border: 1px solid rgba(233, 107, 116, 1);
            color: rgba(227, 77, 89, 1);
          }
          .t-tag--success {
            background: rgba(233, 246, 242, 1);
            border: 1px solid rgba(0, 184, 122, 1);
            color: rgba(0, 184, 122, 1);
          }
        }
      }
      :deep(.t-table__empty) {
        display: none;
      }
      .emptyBox {
        position: absolute;
        height: 116px;
        width: 69px;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        text-align: center;
        .emptyTable-svg-icon {
          height: 62px;
          width: 69px;
        }
        span {
          font-size: 12px;
          font-weight: 400;
          color: rgba(92, 91, 91, 1);
        }
      }
    }
  }
}
.footerBox {
  width: calc(100% - 235px);
  position: absolute;
  bottom: 8px;
  overflow: hidden;
}
:deep(.t-dialog) {
  padding: 22px 22px 18px 22px;
  .t-dialog__body__icon {
    display: none;
  }
  .t-dialog__footer {
    padding-top: 31px;
    .t-dialog__cancel {
      background-color: white;
      border: none;
      width: 60px;
      height: 28px;
    }
    .t-dialog__confirm {
      width: 60px;
      height: 28px;
      opacity: 1;
      border-radius: 3px;
      background: rgba(30, 117, 254, 1);
    }
  }
}
:deep(.ruleDialog .t-dialog__wrap .t-dialog__position .t-dialog) {
  padding: 22px 22px 18px 22px;
  .t-dialog__footer {
    display: none !important;
  }
  .t-dialog__body {
    padding-bottom: 0;
    .t-input {
      height: 28px;
    }
  }
}
:deep(.createDialog .t-dialog__wrap .t-dialog__position .t-dialog) {
  padding: 22px 22px 18px 22px;
  .t-dialog__footer {
    display: none !important;
  }
  .t-dialog__body {
    .t-form__item {
      margin-bottom: 16px;
    }
    .t-form__item:last-child {
      margin-bottom: 0;
      //padding-top: 15px;
    }
    padding-bottom: 0;
    .t-select-input {
      height: 28px;
      .t-tag-input .t-input {
        min-height: 28px;
        .t-tag {
          height: 20px;
        }
      }
    }
    .countInput {
      height: 28px;
      width: 100%;
      .t-input {
        height: 28px;
      }
    }
    .t-select__wrap {
      height: 28px;
      .t-select-input{
        .t-input {
          height: 28px;
        }
      }
    }
  }
}
.handleRuleBox {
  :deep(.t-form__label) {
    font-size: 14px;
    font-weight: 400;
    color: rgba(227, 60, 100, 0.9);

  }
  :deep(.t-form__controls) {
    text-align: right;
  }
  :deep(.t-form__controls-content) {
    display: inline-block;
    position: absolute;
    right: 0;
  }
  .t-button--theme-default {
    background-color: white;
    border: none;
    width: 60px;
    height: 28px;
  }
  .t-button--theme-primary {
    width: 60px;
    height: 28px;
    opacity: 1;
    border-radius: 3px;
    background: rgba(30, 117, 254, 1);
  }
}
// 隐藏为子级的质检项的质检名称
:deep(.t-table-tr--level-1) {
  td {
    div {
      height: 27px !important;
    }
  }
  td:nth-child(1) {
    div {
      overflow: hidden;
      height: 40px;
      content: '';
    }
  }
}

.outAdd {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding-bottom: 15px;
  .titleBtn {
    cursor: pointer;
    margin-left: 0;
    font-size: 11px;
    font-weight: 400;
    color: rgba(30, 117, 254, 1);
    display: flex;
    align-items: center;
    .add-svg-icon {
      height: 16px;
      width: 16px;
      margin-right: 2px;
    }
  }
}
.scrollBox {
  overflow-y: auto;
  max-height: 450px;
}
.outBox {
  padding-bottom: 16px;
  .outHeader {
    height: 35px;
    border-radius: 2px 2px 0 0;
    background: rgba(247, 247, 247, 1);
    margin-bottom: 16px;
    display: flex;
    //justify-content: center;
    align-items: center;
    padding: 0 16px;
    .left {
      font-size: 11px;
      font-weight: 600;
      color: rgba(43, 43, 43, 1);

    }
    .right {
      margin-left: auto;
      font-size: 10px;
      font-weight: 400;
      line-height: 14px;
      color: rgba(245, 115, 126, 1);
      div {
        cursor: pointer;
        display: flex;
        align-items: center;

        .itemDel-svg-icon {
          height: 16px;
          width: 16px;
        }
      }
    }
  }
  border: 1px solid rgba(238, 238, 238, 1);
  margin-bottom: 12px;
  border-radius: 2px;
  :deep(.t-form__item) {
    padding: 0 16px;
  }
  :deep(.t-space) {
    justify-content: center;
    align-items: center;
    .t-space-item:nth-child(1) {
      .t-input__suffix-icon {
        margin-left: 0;
      }
      width: 80px;
    }
    .t-space-item:nth-child(2) {
      font-size: 12px;
      font-weight: 400;
      color: rgba(12, 13, 14, 1);
    }
    .t-space-item:nth-child(3) {
      width: 80px;
    }
    .t-space-item:nth-child(4) {
      width: 80px;
      .t-input__suffix-icon {
        margin-left: 0;
      }
      font-size: 12px;
      font-weight: 400;
      color: rgba(12, 13, 14, 1);
    }
    .t-space-item:nth-child(5) {
      font-size: 12px;
      font-weight: 400;
      color: rgba(12, 13, 14, 1);
    }
  }
}
.headerSonBox {
  display: flex;
  align-items: center;
}
</style>
